﻿using SLEnvironmentSystem;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;

namespace SLBehaviourSystem
{
    [ConditionComponent]
    public class AreaSearchComponent : ConditionComponent
    {
        MoveToTargetComponent move;

        [SerializeField]
        private List<GameObject> gos=new List<GameObject>();

        private float radius;
        EnvironmentArea area;

        protected override void OnInit()
        {
            base.OnInit();
            move = Agent.Components[BehaviourRuntimeComponentType.MoveToTarget] as MoveToTargetComponent;
            area = EnvironmentSystem.Inst.GetArea(Vector3.zero, "Player");
            area.SetSize(new Vector3(radius, 10, radius));
            gos = area.GetGosInArea();
            area.OnChanged += OnGosChanged;
        }

        protected override void OnBindNode()
        {
            radius = node.BehaviourData.GetFloat("Radius");
            area.SetSize(new Vector3(radius, 10, radius));
        }

        private void OnGosChanged()
        {
            ((ConditionNode)node).CheckInterrupt();
        }

        public override BehaviourNodeState Excute()
        {
            Search();
            return gos.Count > 0 ? BehaviourNodeState.Success : BehaviourNodeState.Failure;
        }

        private void Search()
        {
            float minDistance = float.MaxValue;
            float distance = 0;
            for (int i = 0; i < gos.Count; i++)
            {
                distance = Vector3.Distance(transform.position, gos[i].transform.position);
                if (distance < radius
                    && minDistance > distance)
                {
                    minDistance = distance;
                    move.Target = gos[i];
                }
            }
            if (gos.Count==0)
            {
                move.Target = null;
            }
        }
    }
}
